﻿using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace Flare.Pages.Endpoint
{
    public partial class Details : UserControl, IDisposable, ITypicalPage
    {
        public string name
        {
            get { return "Подробнее"; }
        }

        System.Timers.Timer timer_ping_check = new System.Timers.Timer(5000);

        public bool use_remote_control
        {
            get
            {
                return glob.radmin_enable_functions;
            }
        }
        string ip { get; set; }
        int _ep_id;

        public Details(int ep_id)
        {
            _ep_id = ep_id;
            if (glob.radmin_no_found_show_notice && glob.radmin_enable_functions==false)
            {
                glob.kernel.ShowNotice("Не установлен Radmin. Функции удаленного управления будут недоступны");
                glob.radmin_no_found_show_notice = false;
            }

            var details = new Flare.DB.endpoints().Details(ep_id);
            //if ((details.id_type != 1) && (details.id_type != 2))
            //{
            //    use_remote_control = false;
            //}
            this.ip = details.ip;
            this.DataContext = details;

            InitializeComponent();
            
            timer_ping_check.Elapsed += (s, e) =>
            {
                AccessCheck();
            };
            timer_ping_check.Start();

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                AccessCheck();
            });
            
            //if (Flare.Properties.Settings.Default.LastConnectId.Count == 0)
            //{
            //    Flare.Properties.Settings.Default.LastConnectId.Add(ep_id.ToString());
            //    Flare.Properties.Settings.Default.Save();
            //}
            //else {

            //    if (Flare.Properties.Settings.Default.LastConnectId.Contains(ep_id.ToString()) == false)
            //    {
            //        Flare.Properties.Settings.Default.LastConnectId.Insert(0, ep_id.ToString());
            //        Flare.Properties.Settings.Default.Save();
            //    }

            //    if (Flare.Properties.Settings.Default.LastConnectId.Count > 5) {
            //        Flare.Properties.Settings.Default.LastConnectId.RemoveAt(5);
            //    }
            //    //if (Flare.Properties.Settings.Default.LastConnectId.Contains(id.ToString()) == false)
            //    //{
            //    //    Flare.Properties.Settings.Default.LastConnectId.Add(id.ToString());
            //    //    Flare.Properties.Settings.Default.Save();
            //    //}
            //}
            ////log.Text = string.Format(new DB.info_pcs().Index(ip));
            //log.Text = new DB.info_pcs().Index(ip);
        }

        private void AccessCheck()
        {
            var result = new Ping().Send(this.ip, 4000);
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)delegate
             {
                 ui_ping_status.Text = string.Format("({0})", (result.Status == IPStatus.Success) ? "доступен" : "не доступен");
             });
        }

        private void RemoteAdmin_Click(object sender, RoutedEventArgs e)
        {
            StartProg(glob.radmin_exepath, "/connect:" + current_ip.Content);
        }

        private void RemoteView_Click(object sender, RoutedEventArgs e)
        {
            StartProg(glob.radmin_exepath, "/connect:" + current_ip.Content + " /noinput");
        }

        private void RemoteTransfer_Click(object sender, RoutedEventArgs e)
        {
            StartProg(glob.radmin_exepath, "/connect:" + current_ip.Content + " /file");
        }

        private void PingSend_Click(object sender, RoutedEventArgs e)
        {
            StartProg("ping.exe", current_ip.Content + " -t" + " -w 5000");
        }

        void StartProg(string path, string argument)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = path;
            p.StartInfo.Arguments = argument;

            try
            {
                p.Start();
            }
            catch
            {
                glob.kernel.ShowNotice("Ошибка запуска стороннего приложения. Возможно оно отсутствует по предполагаемому пути запуска");
            }
        }

        public void Dispose()
        {
            timer_ping_check.Dispose();
        }

        private void EditThis_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            glob.kernel.ShowPage(typeof(Pages.Endpoint.Edit), _ep_id, replace_current: true);
        }

        private void RemoveThis_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            glob.kernel.ShowPage(typeof(Pages.Endpoint.Delete), _ep_id, replace_current: true);
        }
    }

}
